<template>
  <div class="create-order-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-mask">
      <el-loading v-model="loading" text="正在处理订单..."></el-loading>
    </div>
    
    <!-- 订单确认表单 -->
    <el-card  class="order-card">
      <template #header>
        <div class="card-header">确认订单</div>
      </template>
      
      <div class="order-info">
        <div class="pet-info">
          <el-image 
            :src="animal.imageUrl || defaultImage" 
            class="pet-image" 
            fit="cover"  
            :error="defaultImage"
          ></el-image>
          <div class="pet-details">
            <h3>{{ animal.name }}</h3>
            <p>品种: {{ animal.breed || '未知' }}</p>
            <p>年龄: {{ animal.age || '未知' }}月</p>  <!-- 修正: 年龄单位应为月 -->
            <p>性别: {{ animal.gender === 0 ? '公' : '母' }}</p>
            <p class="price">价格: <span class="price-value">¥{{ animal.price }}</span></p>
          </div>
        </div>
        
        <div class="user-info">
          <h4>用户信息</h4>
          <p>用户名: {{ userInfo?.userName || '未获取到信息' }}</p>
          <p>余额: <span class="balance">¥{{ userInfo?.balance || 0 }}</span></p>
        </div>
        
        <div class="order-summary">
          <p>订单总额: <span class="total-price">¥{{ animal.price }}</span></p>
          <p v-if="userInfo?.balance < animal.price" class="balance-warning">
            <el-icon><WarningFilled /></el-icon>
            您的余额不足，请先充值
          </p>
        </div>
      </div>
      
      <div class="action-buttons">
        <el-button type="primary" @click="createOrder" :disabled="userInfo?.balance < animal.price">
          确认购买
        </el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>
    <!-- 错误状态 -->
   <el-empty description="未找到宠物信息" class="empty-state">
      <el-button type="primary" slot="bottom" @click="goBack">返回</el-button>
    </el-empty>
  </div>

</template>

<script setup>
import { ref, onMounted ,watch} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useUserStore } from '../../stores/userStore'; // 导入用户 store
import { getAnimalByIdApi } from '../../api/animal';
import { createOrderApi } from '../../api/order';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore(); // 获取用户 store 实例
console.log("store",userStore)

// 状态管理
const loading = ref(true);
const animal = ref(null);
const error = ref(null);
const userInfo=ref(null);
// 监听 store 中的用户信息变化
watch(
  () => userStore.userInfo,
  (newUserInfo) => {
    userInfo.value = newUserInfo;
    console.log('用户信息已更新:', userInfo.value);
  },
  { immediate: true } // 立即执行一次，获取初始值
);

const fetchUserInfo = async () => {
  try {
    await userStore.fetchCurrentUser();
    userInfo.value = userStore.userInfo; // 更新组件中的用户信息
    console.log("userInfo:",userInfo);
  } catch (error) {
    ElMessage.error('获取用户信息失败，请重试');
    if (error.response && error.response.status === 401) {
      router.push({ name: 'Login' });
    }
  }
};
// 加载所有数据


// 获取宠物信息
const fetchAnimalInfo = async () => {
  try {
    const animalId = route.params.id;
    
    if (!animalId) {
      throw new Error('无效的宠物ID');
    }
    const response = await getAnimalByIdApi(animalId);

      animal.value = response;
    console.log('【API响应】数据:', response.data);
    }
    catch (error) {
    console.error('获取宠物信息出错:', error);
    ElMessage.error('获取宠物信息失败，请重试');
    router.back();}
};
console.log("animal",animal.value);
// 加载所有数据
const loadData = async () => {
  try {
    loading.value = true;
    
    // 检查用户是否登录
    if (!userStore.isLoggedIn) { // 使用 store 的 getter
      ElMessage.error('请先登录');
      router.push({ name: 'Login' });
      return;
    }
    // 并行获取用户和宠物信息
    await Promise.all([fetchUserInfo(), fetchAnimalInfo()]);
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('加载数据失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 创建订单
const createOrder = async () => {
  if (!animal.value || !userInfo.value) return;
  
  try {
    loading.value = true;
    
    const orderData = {
      animalId: animal.value.id,
      // 可以添加其他订单信息
    };
    
    const response = await createOrderApi(orderData);
    
    if (response.code === 0) {
      ElMessage.success('订单创建成功');
      // 跳转到订单详情页
      router.push({ name: 'OrderDetail', params: { orderId: response.data.id } });
    } else if (response.code === 40001) {
      // 余额不足的情况
      ElMessage.warning('余额不足，即将跳转到充值页面');
      setTimeout(() => {
        router.push({ name: 'Recharge' });
      }, 1500);
    } else {
      ElMessage.error(response.message || '创建订单失败');
    }
  } catch (error) {
    console.error('创建订单失败:', error);
    ElMessage.error('创建订单失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});
</script>



<style scoped>
.create-order-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.order-card {
  margin-top: 20px;
}

.pet-info {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.pet-image {
  width: 150px;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
}

.pet-details {
  flex: 1;
}

.price {
  color: #f56c6c;
  font-size: 16px;
  margin-top: 10px;
}

.price-value {
  font-weight: bold;
  font-size: 18px;
}

.user-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9fafc;
  border-radius: 4px;
}

.balance {
  color: #67c23a;
  font-weight: bold;
}

.order-summary {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.total-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.balance-warning {
  color: #f56c6c;
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.empty-state {
  margin-top: 50px;
}
</style>